﻿using Core.Framework.Model.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System.Collections.Generic;

namespace Core.Middleware.ApiJson
{
    public class ApiJsonDbContext
    {

        public SqlSugarClient Db;


        public ApiJsonDbContext(HttpContext httpContext)
        {

            IApiJsonDbContextParameter options = this.GetContextParameter(httpContext?.Request.Headers);

            if (null == options)
            {
                throw new System.Exception("未匹配到 Header Itool-Data 指定的数据选区");
            }

            Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = options.ConnectionString,
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });
        }


        /// <summary>
        /// 构造数据库连接参数
        /// </summary>
        /// <param name="databaseName"></param>
        /// <returns></returns>
        private ApiJsonDbContextParameter GetContextParameter(IHeaderDictionary header)
        {

            var databaseName = header?["Itool-Data"].ToString() ?? "AppInfo_SqlServerConnection";

            if (string.IsNullOrWhiteSpace(databaseName))
            {
                return null;
            }

            var connstr = CoreStartupHelper.GetConnectionValue(databaseName);

            if (string.IsNullOrWhiteSpace(connstr))
            {
                return null;
            }

            return new ApiJsonDbContextParameter
            {
                ConnectionString = connstr
            };
        }
    }

    public class DbSet<T> : SimpleClient<T> where T : class, new()
    {
        public DbSet(SqlSugarClient context) : base(context)
        {

        }
        public List<T> GetByIds(dynamic[] ids)
        {
            return Context.Queryable<T>().In(ids).ToList(); ;
        }
    }

}
